{
  "cells": [
    {
      "cell_type": "raw",
      "id": "afaf8039",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: Anthropic\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e49f1e0d",
      "metadata": {},
      "source": [
        "# ChatAnthropic\n",
        "\n",
        "[Anthropic](https://www.anthropic.com/) is an AI safety and research company. They are the creator of Claude.\n",
        "\n",
        "This will help you getting started with Anthropic [chat models](/docs/concepts/chat_models). For detailed documentation of all `ChatAnthropic` features and configurations head to the [API reference](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html).\n",
        "\n",
        "## Overview\n",
        "### Integration details\n",
        "\n",
        "| Class | Package | Local | Serializable | [PY support](https://python.langchain.com/docs/integrations/chat/anthropic/) | Package downloads | Package latest |\n",
        "| :--- | :--- | :---: | :---: |  :---: | :---: | :---: |\n",
        "| [ChatAnthropic](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) | [`@langchain/anthropic`](https://www.npmjs.com/package/@langchain/anthropic) | ❌ | ✅ | ✅ | ![NPM - Downloads](https://img.shields.io/npm/dm/@langchain/anthropic?style=flat-square&label=%20&) | ![NPM - Version](https://img.shields.io/npm/v/@langchain/anthropic?style=flat-square&label=%20&) |\n",
        "\n",
        "### Model features\n",
        "\n",
        "See the links in the table headers below for guides on how to use specific features.\n",
        "\n",
        "| [Tool calling](/docs/how_to/tool_calling) | [Structured output](/docs/how_to/structured_output/) | JSON mode | [Image input](/docs/how_to/multimodal_inputs/) | Audio input | Video input | [Token-level streaming](/docs/how_to/chat_streaming/) | [Token usage](/docs/how_to/chat_token_usage_tracking/) | [Logprobs](/docs/how_to/logprobs/) |\n",
        "| :---: | :---: | :---: | :---: |  :---: | :---: | :---: | :---: | :---: |\n",
        "| ✅ | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | \n",
        "\n",
        "## Setup\n",
        "\n",
        "You'll need to sign up and obtain an [Anthropic API key](https://www.anthropic.com/), and install the `@langchain/anthropic` integration package.\n",
        "\n",
        "### Credentials\n",
        "\n",
        "Head to [Anthropic's website](https://www.anthropic.com/) to sign up to Anthropic and generate an API key. Once you've done this set the `ANTHROPIC_API_KEY` environment variable:\n",
        "\n",
        "```bash\n",
        "export ANTHROPIC_API_KEY=\"your-api-key\"\n",
        "```\n",
        "\n",
        "If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "```bash\n",
        "# export LANGSMITH_TRACING=\"true\"\n",
        "# export LANGSMITH_API_KEY=\"your-api-key\"\n",
        "```\n",
        "\n",
        "### Installation\n",
        "\n",
        "The LangChain `ChatAnthropic` integration lives in the `@langchain/anthropic` package:\n",
        "\n",
        "```{=mdx}\n",
        "\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/anthropic @langchain/core\n",
        "</Npm2Yarn>\n",
        "\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a38cde65-254d-4219-a441-068766c0d4b5",
      "metadata": {},
      "source": [
        "## Instantiation\n",
        "\n",
        "Now we can instantiate our model object and generate chat completions:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "cb09c344-1836-4e0c-acf8-11d13ac1dbae",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\" \n",
        "\n",
        "const llm = new ChatAnthropic({\n",
        "    model: \"claude-3-haiku-20240307\",\n",
        "    temperature: 0,\n",
        "    maxTokens: undefined,\n",
        "    maxRetries: 2,\n",
        "    // other params...\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2b4f3e15",
      "metadata": {},
      "source": [
        "## Invocation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "62e0dbc3",
      "metadata": {
        "tags": []
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AIMessage {\n",
            "  \"id\": \"msg_013WBXXiggy6gMbAUY6NpsuU\",\n",
            "  \"content\": \"Voici la traduction en français :\\n\\nJ'adore la programmation.\",\n",
            "  \"additional_kwargs\": {\n",
            "    \"id\": \"msg_013WBXXiggy6gMbAUY6NpsuU\",\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\",\n",
            "    \"model\": \"claude-3-haiku-20240307\",\n",
            "    \"stop_reason\": \"end_turn\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 29,\n",
            "      \"output_tokens\": 20\n",
            "    }\n",
            "  },\n",
            "  \"response_metadata\": {\n",
            "    \"id\": \"msg_013WBXXiggy6gMbAUY6NpsuU\",\n",
            "    \"model\": \"claude-3-haiku-20240307\",\n",
            "    \"stop_reason\": \"end_turn\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 29,\n",
            "      \"output_tokens\": 20\n",
            "    },\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\"\n",
            "  },\n",
            "  \"tool_calls\": [],\n",
            "  \"invalid_tool_calls\": [],\n",
            "  \"usage_metadata\": {\n",
            "    \"input_tokens\": 29,\n",
            "    \"output_tokens\": 20,\n",
            "    \"total_tokens\": 49\n",
            "  }\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "const aiMsg = await llm.invoke([\n",
        "    [\n",
        "        \"system\",\n",
        "        \"You are a helpful assistant that translates English to French. Translate the user sentence.\",\n",
        "    ],\n",
        "    [\"human\", \"I love programming.\"],\n",
        "])\n",
        "aiMsg"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "d86145b3-bfef-46e8-b227-4dda5c9c2705",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Voici la traduction en français :\n",
            "\n",
            "J'adore la programmation.\n"
          ]
        }
      ],
      "source": [
        "console.log(aiMsg.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "18e2bfc0-7e78-4528-a73f-499ac150dca8",
      "metadata": {},
      "source": [
        "## Chaining\n",
        "\n",
        "We can [chain](/docs/how_to/sequence/) our model with a prompt template like so:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "e197d1d7-a070-4c96-9f8a-a0e86d046e0b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AIMessage {\n",
            "  \"id\": \"msg_01Ca52fpd1mcGRhH4spzAWr4\",\n",
            "  \"content\": \"Ich liebe das Programmieren.\",\n",
            "  \"additional_kwargs\": {\n",
            "    \"id\": \"msg_01Ca52fpd1mcGRhH4spzAWr4\",\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\",\n",
            "    \"model\": \"claude-3-haiku-20240307\",\n",
            "    \"stop_reason\": \"end_turn\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 23,\n",
            "      \"output_tokens\": 11\n",
            "    }\n",
            "  },\n",
            "  \"response_metadata\": {\n",
            "    \"id\": \"msg_01Ca52fpd1mcGRhH4spzAWr4\",\n",
            "    \"model\": \"claude-3-haiku-20240307\",\n",
            "    \"stop_reason\": \"end_turn\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 23,\n",
            "      \"output_tokens\": 11\n",
            "    },\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\"\n",
            "  },\n",
            "  \"tool_calls\": [],\n",
            "  \"invalid_tool_calls\": [],\n",
            "  \"usage_metadata\": {\n",
            "    \"input_tokens\": 23,\n",
            "    \"output_tokens\": 11,\n",
            "    \"total_tokens\": 34\n",
            "  }\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\"\n",
        "\n",
        "const prompt = ChatPromptTemplate.fromMessages(\n",
        "    [\n",
        "        [\n",
        "            \"system\",\n",
        "            \"You are a helpful assistant that translates {input_language} to {output_language}.\",\n",
        "        ],\n",
        "        [\"human\", \"{input}\"],\n",
        "    ]\n",
        ")\n",
        "\n",
        "const chain = prompt.pipe(llm);\n",
        "await chain.invoke(\n",
        "    {\n",
        "        input_language: \"English\",\n",
        "        output_language: \"German\",\n",
        "        input: \"I love programming.\",\n",
        "    }\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8dac39db",
      "metadata": {},
      "source": [
        "## Content blocks\n",
        "\n",
        "One key difference to note between Anthropic models and most others is that the contents of a single Anthropic AI message can either be a single string or a **list of content blocks**. For example when an Anthropic model [calls a tool](/docs/how_to/tool_calling), the tool invocation is part of the message content (as well as being exposed in the standardized `AIMessage.tool_calls` field):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "f5994de0",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AIMessage {\n",
            "  \"id\": \"msg_01DZGs9DyuashaYxJ4WWpWUP\",\n",
            "  \"content\": [\n",
            "    {\n",
            "      \"type\": \"text\",\n",
            "      \"text\": \"Here is the calculation for 2 + 2:\"\n",
            "    },\n",
            "    {\n",
            "      \"type\": \"tool_use\",\n",
            "      \"id\": \"toolu_01SQXBamkBr6K6NdHE7GWwF8\",\n",
            "      \"name\": \"calculator\",\n",
            "      \"input\": {\n",
            "        \"number1\": 2,\n",
            "        \"number2\": 2,\n",
            "        \"operation\": \"add\"\n",
            "      }\n",
            "    }\n",
            "  ],\n",
            "  \"additional_kwargs\": {\n",
            "    \"id\": \"msg_01DZGs9DyuashaYxJ4WWpWUP\",\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\",\n",
            "    \"model\": \"claude-3-haiku-20240307\",\n",
            "    \"stop_reason\": \"tool_use\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 449,\n",
            "      \"output_tokens\": 100\n",
            "    }\n",
            "  },\n",
            "  \"response_metadata\": {\n",
            "    \"id\": \"msg_01DZGs9DyuashaYxJ4WWpWUP\",\n",
            "    \"model\": \"claude-3-haiku-20240307\",\n",
            "    \"stop_reason\": \"tool_use\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 449,\n",
            "      \"output_tokens\": 100\n",
            "    },\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\"\n",
            "  },\n",
            "  \"tool_calls\": [\n",
            "    {\n",
            "      \"name\": \"calculator\",\n",
            "      \"args\": {\n",
            "        \"number1\": 2,\n",
            "        \"number2\": 2,\n",
            "        \"operation\": \"add\"\n",
            "      },\n",
            "      \"id\": \"toolu_01SQXBamkBr6K6NdHE7GWwF8\",\n",
            "      \"type\": \"tool_call\"\n",
            "    }\n",
            "  ],\n",
            "  \"invalid_tool_calls\": [],\n",
            "  \"usage_metadata\": {\n",
            "    \"input_tokens\": 449,\n",
            "    \"output_tokens\": 100,\n",
            "    \"total_tokens\": 549\n",
            "  }\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "import { z } from \"zod\";\n",
        "import { zodToJsonSchema } from \"zod-to-json-schema\";\n",
        "\n",
        "const calculatorSchema = z.object({\n",
        "  operation: z\n",
        "    .enum([\"add\", \"subtract\", \"multiply\", \"divide\"])\n",
        "    .describe(\"The type of operation to execute.\"),\n",
        "  number1: z.number().describe(\"The first number to operate on.\"),\n",
        "  number2: z.number().describe(\"The second number to operate on.\"),\n",
        "});\n",
        "\n",
        "const calculatorTool = {\n",
        "  name: \"calculator\",\n",
        "  description: \"A simple calculator tool\",\n",
        "  input_schema: zodToJsonSchema(calculatorSchema),\n",
        "};\n",
        "\n",
        "const toolCallingLlm = new ChatAnthropic({\n",
        "  model: \"claude-3-haiku-20240307\",\n",
        "}).bindTools([calculatorTool]);\n",
        "\n",
        "const toolPrompt = ChatPromptTemplate.fromMessages([\n",
        "  [\n",
        "    \"system\",\n",
        "    \"You are a helpful assistant who always needs to use a calculator.\",\n",
        "  ],\n",
        "  [\"human\", \"{input}\"],\n",
        "]);\n",
        "\n",
        "// Chain your prompt and model together\n",
        "const toolCallChain = toolPrompt.pipe(toolCallingLlm);\n",
        "\n",
        "await toolCallChain.invoke({\n",
        "  input: \"What is 2 + 2?\",\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d452d4b6",
      "metadata": {},
      "source": [
        "## Custom headers\n",
        "\n",
        "You can pass custom headers in your requests like this:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "41943f0a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AIMessage {\n",
            "  \"id\": \"msg_019z4nWpShzsrbSHTWXWQh6z\",\n",
            "  \"content\": \"The sky appears blue due to a phenomenon called Rayleigh scattering. Here's a brief explanation:\\n\\n1) Sunlight is made up of different wavelengths of visible light, including all the colors of the rainbow.\\n\\n2) As sunlight passes through the atmosphere, the gases (mostly nitrogen and oxygen) cause the shorter wavelengths of light, such as violet and blue, to be scattered more easily than the longer wavelengths like red and orange.\\n\\n3) This scattering of the shorter blue wavelengths occurs in all directions by the gas molecules in the atmosphere.\\n\\n4) Our eyes are more sensitive to the scattered blue light than the scattered violet light, so we perceive the sky as having a blue color.\\n\\n5) The scattering is more pronounced for light traveling over longer distances through the atmosphere. This is why the sky appears even darker blue when looking towards the horizon.\\n\\nSo in essence, the selective scattering of the shorter blue wavelengths of sunlight by the gases in the atmosphere is what causes the sky to appear blue to our eyes during the daytime.\",\n",
            "  \"additional_kwargs\": {\n",
            "    \"id\": \"msg_019z4nWpShzsrbSHTWXWQh6z\",\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\",\n",
            "    \"model\": \"claude-3-sonnet-20240229\",\n",
            "    \"stop_reason\": \"end_turn\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 13,\n",
            "      \"output_tokens\": 236\n",
            "    }\n",
            "  },\n",
            "  \"response_metadata\": {\n",
            "    \"id\": \"msg_019z4nWpShzsrbSHTWXWQh6z\",\n",
            "    \"model\": \"claude-3-sonnet-20240229\",\n",
            "    \"stop_reason\": \"end_turn\",\n",
            "    \"stop_sequence\": null,\n",
            "    \"usage\": {\n",
            "      \"input_tokens\": 13,\n",
            "      \"output_tokens\": 236\n",
            "    },\n",
            "    \"type\": \"message\",\n",
            "    \"role\": \"assistant\"\n",
            "  },\n",
            "  \"tool_calls\": [],\n",
            "  \"invalid_tool_calls\": [],\n",
            "  \"usage_metadata\": {\n",
            "    \"input_tokens\": 13,\n",
            "    \"output_tokens\": 236,\n",
            "    \"total_tokens\": 249\n",
            "  }\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "\n",
        "const llmWithCustomHeaders = new ChatAnthropic({\n",
        "  model: \"claude-3-sonnet-20240229\",\n",
        "  maxTokens: 1024,\n",
        "  clientOptions: {\n",
        "    defaultHeaders: {\n",
        "      \"X-Api-Key\": process.env.ANTHROPIC_API_KEY,\n",
        "    },\n",
        "  },\n",
        "});\n",
        "\n",
        "await llmWithCustomHeaders.invoke(\"Why is the sky blue?\");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3c5e6d7a",
      "metadata": {},
      "source": [
        "## Prompt caching\n",
        "\n",
        "```{=mdx}\n",
        "\n",
        ":::caution Compatibility\n",
        "This feature is currently in beta.\n",
        ":::\n",
        "\n",
        "```\n",
        "\n",
        "Anthropic supports [caching parts of your prompt](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching) in order to reduce costs for use-cases that require long context. You can cache tools and both entire messages and individual blocks.\n",
        "\n",
        "The initial request containing one or more blocks or tool definitions with a `\"cache_control\": { \"type\": \"ephemeral\" }` field will automatically cache that part of the prompt. This initial caching step will cost extra, but subsequent requests will be billed at a reduced rate. The cache has a lifetime of 5 minutes, but this is refereshed each time the cache is hit.\n",
        "\n",
        "There is also currently a minimum cacheable prompt length, which varies according to model. You can see this information [here](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching#structuring-your-prompt).\n",
        "\n",
        "This currently requires you to initialize your model with a beta header. Here's an example of caching part of a system message that contains the LangChain [conceptual docs](/docs/concepts/):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "5e02b056",
      "metadata": {},
      "outputs": [],
      "source": [
        "let CACHED_TEXT = \"...\";"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "bba739ed",
      "metadata": {},
      "outputs": [],
      "source": [
        "// @lc-docs-hide-cell\n",
        "\n",
        "CACHED_TEXT = `## Components\n",
        "\n",
        "LangChain provides standard, extendable interfaces and external integrations for various components useful for building with LLMs.\n",
        "Some components LangChain implements, some components we rely on third-party integrations for, and others are a mix.\n",
        "\n",
        "### Chat models\n",
        "\n",
        "<span data-heading-keywords=\"chat model,chat models\"></span>\n",
        "\n",
        "Language models that use a sequence of messages as inputs and return chat messages as outputs (as opposed to using plain text).\n",
        "These are generally newer models (older models are generally \\`LLMs\\`, see below).\n",
        "Chat models support the assignment of distinct roles to conversation messages, helping to distinguish messages from the AI, users, and instructions such as system messages.\n",
        "\n",
        "Although the underlying models are messages in, message out, the LangChain wrappers also allow these models to take a string as input.\n",
        "This gives them the same interface as LLMs (and simpler to use).\n",
        "When a string is passed in as input, it will be converted to a \\`HumanMessage\\` under the hood before being passed to the underlying model.\n",
        "\n",
        "LangChain does not host any Chat Models, rather we rely on third party integrations.\n",
        "\n",
        "We have some standardized parameters when constructing ChatModels:\n",
        "\n",
        "- \\`model\\`: the name of the model\n",
        "\n",
        "Chat Models also accept other parameters that are specific to that integration.\n",
        "\n",
        ":::important\n",
        "Some chat models have been fine-tuned for **tool calling** and provide a dedicated API for it.\n",
        "Generally, such models are better at tool calling than non-fine-tuned models, and are recommended for use cases that require tool calling.\n",
        "Please see the [tool calling section](/docs/concepts/tool_calling) for more information.\n",
        ":::\n",
        "\n",
        "For specifics on how to use chat models, see the [relevant how-to guides here](/docs/how_to/#chat-models).\n",
        "\n",
        "#### Multimodality\n",
        "\n",
        "Some chat models are multimodal, accepting images, audio and even video as inputs.\n",
        "These are still less common, meaning model providers haven't standardized on the \"best\" way to define the API.\n",
        "Multimodal outputs are even less common. As such, we've kept our multimodal abstractions fairly light weight\n",
        "and plan to further solidify the multimodal APIs and interaction patterns as the field matures.\n",
        "\n",
        "In LangChain, most chat models that support multimodal inputs also accept those values in OpenAI's content blocks format.\n",
        "So far this is restricted to image inputs. For models like Gemini which support video and other bytes input, the APIs also support the native, model-specific representations.\n",
        "\n",
        "For specifics on how to use multimodal models, see the [relevant how-to guides here](/docs/how_to/#multimodal).\n",
        "\n",
        "### LLMs\n",
        "\n",
        "<span data-heading-keywords=\"llm,llms\"></span>\n",
        "\n",
        ":::caution\n",
        "Pure text-in/text-out LLMs tend to be older or lower-level. Many popular models are best used as [chat completion models](/docs/concepts/chat_models),\n",
        "even for non-chat use cases.\n",
        "\n",
        "You are probably looking for [the section above instead](/docs/concepts/chat_models).\n",
        ":::\n",
        "\n",
        "Language models that takes a string as input and returns a string.\n",
        "These are traditionally older models (newer models generally are [Chat Models](/docs/concepts/chat_models), see above).\n",
        "\n",
        "Although the underlying models are string in, string out, the LangChain wrappers also allow these models to take messages as input.\n",
        "This gives them the same interface as [Chat Models](/docs/concepts/chat_models).\n",
        "When messages are passed in as input, they will be formatted into a string under the hood before being passed to the underlying model.\n",
        "\n",
        "LangChain does not host any LLMs, rather we rely on third party integrations.\n",
        "\n",
        "For specifics on how to use LLMs, see the [relevant how-to guides here](/docs/how_to/#llms).\n",
        "\n",
        "### Message types\n",
        "\n",
        "Some language models take an array of messages as input and return a message.\n",
        "There are a few different types of messages.\n",
        "All messages have a \\`role\\`, \\`content\\`, and \\`response_metadata\\` property.\n",
        "\n",
        "The \\`role\\` describes WHO is saying the message.\n",
        "LangChain has different message classes for different roles.\n",
        "\n",
        "The \\`content\\` property describes the content of the message.\n",
        "This can be a few different things:\n",
        "\n",
        "- A string (most models deal this type of content)\n",
        "- A List of objects (this is used for multi-modal input, where the object contains information about that input type and that input location)\n",
        "\n",
        "#### HumanMessage\n",
        "\n",
        "This represents a message from the user.\n",
        "\n",
        "#### AIMessage\n",
        "\n",
        "This represents a message from the model. In addition to the \\`content\\` property, these messages also have:\n",
        "\n",
        "**\\`response_metadata\\`**\n",
        "\n",
        "The \\`response_metadata\\` property contains additional metadata about the response. The data here is often specific to each model provider.\n",
        "This is where information like log-probs and token usage may be stored.\n",
        "\n",
        "**\\`tool_calls\\`**\n",
        "\n",
        "These represent a decision from an language model to call a tool. They are included as part of an \\`AIMessage\\` output.\n",
        "They can be accessed from there with the \\`.tool_calls\\` property.\n",
        "\n",
        "This property returns a list of \\`ToolCall\\`s. A \\`ToolCall\\` is an object with the following arguments:\n",
        "\n",
        "- \\`name\\`: The name of the tool that should be called.\n",
        "- \\`args\\`: The arguments to that tool.\n",
        "- \\`id\\`: The id of that tool call.\n",
        "\n",
        "#### SystemMessage\n",
        "\n",
        "This represents a system message, which tells the model how to behave. Not every model provider supports this.\n",
        "\n",
        "#### ToolMessage\n",
        "\n",
        "This represents the result of a tool call. In addition to \\`role\\` and \\`content\\`, this message has:\n",
        "\n",
        "- a \\`tool_call_id\\` field which conveys the id of the call to the tool that was called to produce this result.\n",
        "- an \\`artifact\\` field which can be used to pass along arbitrary artifacts of the tool execution which are useful to track but which should not be sent to the model.\n",
        "\n",
        "#### (Legacy) FunctionMessage\n",
        "\n",
        "This is a legacy message type, corresponding to OpenAI's legacy function-calling API. \\`ToolMessage\\` should be used instead to correspond to the updated tool-calling API.\n",
        "\n",
        "This represents the result of a function call. In addition to \\`role\\` and \\`content\\`, this message has a \\`name\\` parameter which conveys the name of the function that was called to produce this result.\n",
        "\n",
        "### Prompt templates\n",
        "\n",
        "<span data-heading-keywords=\"prompt,prompttemplate,chatprompttemplate\"></span>\n",
        "\n",
        "Prompt templates help to translate user input and parameters into instructions for a language model.\n",
        "This can be used to guide a model's response, helping it understand the context and generate relevant and coherent language-based output.\n",
        "\n",
        "Prompt Templates take as input an object, where each key represents a variable in the prompt template to fill in.\n",
        "\n",
        "Prompt Templates output a PromptValue. This PromptValue can be passed to an LLM or a ChatModel, and can also be cast to a string or an array of messages.\n",
        "The reason this PromptValue exists is to make it easy to switch between strings and messages.\n",
        "\n",
        "There are a few different types of prompt templates:\n",
        "\n",
        "#### String PromptTemplates\n",
        "\n",
        "These prompt templates are used to format a single string, and generally are used for simpler inputs.\n",
        "For example, a common way to construct and use a PromptTemplate is as follows:\n",
        "\n",
        "\\`\\`\\`typescript\n",
        "import { PromptTemplate } from \"@langchain/core/prompts\";\n",
        "\n",
        "const promptTemplate = PromptTemplate.fromTemplate(\n",
        "  \"Tell me a joke about {topic}\"\n",
        ");\n",
        "\n",
        "await promptTemplate.invoke({ topic: \"cats\" });\n",
        "\\`\\`\\`\n",
        "\n",
        "#### ChatPromptTemplates\n",
        "\n",
        "These prompt templates are used to format an array of messages. These \"templates\" consist of an array of templates themselves.\n",
        "For example, a common way to construct and use a ChatPromptTemplate is as follows:\n",
        "\n",
        "\\`\\`\\`typescript\n",
        "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
        "\n",
        "const promptTemplate = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", \"You are a helpful assistant\"],\n",
        "  [\"user\", \"Tell me a joke about {topic}\"],\n",
        "]);\n",
        "\n",
        "await promptTemplate.invoke({ topic: \"cats\" });\n",
        "\\`\\`\\`\n",
        "\n",
        "In the above example, this ChatPromptTemplate will construct two messages when called.\n",
        "The first is a system message, that has no variables to format.\n",
        "The second is a HumanMessage, and will be formatted by the \\`topic\\` variable the user passes in.\n",
        "\n",
        "#### MessagesPlaceholder\n",
        "\n",
        "<span data-heading-keywords=\"messagesplaceholder\"></span>\n",
        "\n",
        "This prompt template is responsible for adding an array of messages in a particular place.\n",
        "In the above ChatPromptTemplate, we saw how we could format two messages, each one a string.\n",
        "But what if we wanted the user to pass in an array of messages that we would slot into a particular spot?\n",
        "This is how you use MessagesPlaceholder.\n",
        "\n",
        "\\`\\`\\`typescript\n",
        "import {\n",
        "  ChatPromptTemplate,\n",
        "  MessagesPlaceholder,\n",
        "} from \"@langchain/core/prompts\";\n",
        "import { HumanMessage } from \"@langchain/core/messages\";\n",
        "\n",
        "const promptTemplate = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", \"You are a helpful assistant\"],\n",
        "  new MessagesPlaceholder(\"msgs\"),\n",
        "]);\n",
        "\n",
        "promptTemplate.invoke({ msgs: [new HumanMessage({ content: \"hi!\" })] });\n",
        "\\`\\`\\`\n",
        "\n",
        "This will produce an array of two messages, the first one being a system message, and the second one being the HumanMessage we passed in.\n",
        "If we had passed in 5 messages, then it would have produced 6 messages in total (the system message plus the 5 passed in).\n",
        "This is useful for letting an array of messages be slotted into a particular spot.\n",
        "\n",
        "An alternative way to accomplish the same thing without using the \\`MessagesPlaceholder\\` class explicitly is:\n",
        "\n",
        "\\`\\`\\`typescript\n",
        "const promptTemplate = ChatPromptTemplate.fromMessages([\n",
        "  [\"system\", \"You are a helpful assistant\"],\n",
        "  [\"placeholder\", \"{msgs}\"], // <-- This is the changed part\n",
        "]);\n",
        "\\`\\`\\`\n",
        "\n",
        "For specifics on how to use prompt templates, see the [relevant how-to guides here](/docs/how_to/#prompt-templates).\n",
        "\n",
        "### Example Selectors\n",
        "\n",
        "One common prompting technique for achieving better performance is to include examples as part of the prompt.\n",
        "This gives the language model concrete examples of how it should behave.\n",
        "Sometimes these examples are hardcoded into the prompt, but for more advanced situations it may be nice to dynamically select them.\n",
        "Example Selectors are classes responsible for selecting and then formatting examples into prompts.\n",
        "\n",
        "For specifics on how to use example selectors, see the [relevant how-to guides here](/docs/how_to/#example-selectors).\n",
        "\n",
        "### Output parsers\n",
        "\n",
        "<span data-heading-keywords=\"output parser\"></span>\n",
        "\n",
        ":::note\n",
        "\n",
        "The information here refers to parsers that take a text output from a model try to parse it into a more structured representation.\n",
        "More and more models are supporting function (or tool) calling, which handles this automatically.\n",
        "It is recommended to use function/tool calling rather than output parsing.\n",
        "See documentation for that [here](/docs/concepts/tool_calling).\n",
        "\n",
        ":::\n",
        "\n",
        "Responsible for taking the output of a model and transforming it to a more suitable format for downstream tasks.\n",
        "Useful when you are using LLMs to generate structured data, or to normalize output from chat models and LLMs.\n",
        "\n",
        "There are two main methods an output parser must implement:\n",
        "\n",
        "- \"Get format instructions\": A method which returns a string containing instructions for how the output of a language model should be formatted.\n",
        "- \"Parse\": A method which takes in a string (assumed to be the response from a language model) and parses it into some structure.\n",
        "\n",
        "And then one optional one:\n",
        "\n",
        "- \"Parse with prompt\": A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to be the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so.\n",
        "\n",
        "Output parsers accept a string or \\`BaseMessage\\` as input and can return an arbitrary type.\n",
        "\n",
        "LangChain has many different types of output parsers. This is a list of output parsers LangChain supports. The table below has various pieces of information:\n",
        "\n",
        "**Name**: The name of the output parser\n",
        "\n",
        "**Supports Streaming**: Whether the output parser supports streaming.\n",
        "\n",
        "**Input Type**: Expected input type. Most output parsers work on both strings and messages, but some (like OpenAI Functions) need a message with specific arguments.\n",
        "\n",
        "**Output Type**: The output type of the object returned by the parser.\n",
        "\n",
        "**Description**: Our commentary on this output parser and when to use it.\n",
        "\n",
        "The current date is ${new Date().toISOString()}`;\n",
        "\n",
        "// Noop statement to hide output\n",
        "void 0;"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "6e47de9b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "USAGE: {\n",
            "  input_tokens: 19,\n",
            "  cache_creation_input_tokens: 2921,\n",
            "  cache_read_input_tokens: 0,\n",
            "  output_tokens: 355\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "\n",
        "const modelWithCaching = new ChatAnthropic({\n",
        "  model: \"claude-3-haiku-20240307\",\n",
        "  clientOptions: {\n",
        "    defaultHeaders: {\n",
        "      \"anthropic-beta\": \"prompt-caching-2024-07-31\",\n",
        "    },\n",
        "  },\n",
        "});\n",
        "\n",
        "const LONG_TEXT = `You are a pirate. Always respond in pirate dialect.\n",
        "\n",
        "Use the following as context when answering questions:\n",
        "\n",
        "${CACHED_TEXT}`;\n",
        "\n",
        "const messages = [\n",
        "  {\n",
        "    role: \"system\",\n",
        "    content: [\n",
        "      {\n",
        "        type: \"text\",\n",
        "        text: LONG_TEXT,\n",
        "        // Tell Anthropic to cache this block\n",
        "        cache_control: { type: \"ephemeral\" },\n",
        "      },\n",
        "    ],\n",
        "  },\n",
        "  {\n",
        "    role: \"user\",\n",
        "    content: \"What types of messages are supported in LangChain?\",\n",
        "  },\n",
        "];\n",
        "\n",
        "const res = await modelWithCaching.invoke(messages);\n",
        "\n",
        "console.log(\"USAGE:\", res.response_metadata.usage);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "826d95b6",
      "metadata": {},
      "source": [
        "We can see that there's a new field called `cache_creation_input_tokens` in the raw usage field returned from Anthropic.\n",
        "\n",
        "If we use the same messages again, we can see that the long text's input tokens are read from the cache:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "5d264f8b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "USAGE: {\n",
            "  input_tokens: 19,\n",
            "  cache_creation_input_tokens: 0,\n",
            "  cache_read_input_tokens: 2921,\n",
            "  output_tokens: 357\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "const res2 = await modelWithCaching.invoke(messages);\n",
        "\n",
        "console.log(\"USAGE:\", res2.response_metadata.usage);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fc6bba1b",
      "metadata": {},
      "source": [
        "### Tool caching\n",
        "\n",
        "You can also cache tools by setting the same `\"cache_control\": { \"type\": \"ephemeral\" }` within a tool definition. This currently requires you to bind a tool in [Anthropic's raw tool format](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) Here's an example:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "9c7c5eaf",
      "metadata": {},
      "outputs": [],
      "source": [
        "const SOME_LONG_DESCRIPTION = \"...\";\n",
        "\n",
        "// Tool in Anthropic format\n",
        "const anthropicTools = [{\n",
        "  name: \"get_weather\",\n",
        "  description: SOME_LONG_DESCRIPTION,\n",
        "  input_schema: {\n",
        "    type: \"object\",\n",
        "    properties: {\n",
        "      location: {\n",
        "        type: \"string\",\n",
        "        description: \"Location to get the weather for\",\n",
        "      },\n",
        "      unit: {\n",
        "        type: \"string\",\n",
        "        description: \"Temperature unit to return\",\n",
        "      },\n",
        "    },\n",
        "    required: [\"location\"],\n",
        "  },\n",
        "  // Tell Anthropic to cache this tool\n",
        "  cache_control: { type: \"ephemeral\" },\n",
        "}]\n",
        "\n",
        "const modelWithCachedTools = modelWithCaching.bindTools(anthropicTools);\n",
        "\n",
        "await modelWithCachedTools.invoke(\"what is the weather in SF?\");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5d000dd9",
      "metadata": {},
      "source": [
        "\n",
        "\n",
        "For more on how prompt caching works, see [Anthropic's docs](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching#how-prompt-caching-works)."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f8dece4e",
      "metadata": {},
      "source": [
        "## Custom clients\n",
        "\n",
        "Anthropic models [may be hosted on cloud services such as Google Vertex](https://docs.anthropic.com/en/api/claude-on-vertex-ai) that rely on a different underlying client with the same interface as the primary Anthropic client. You can access these services by providing a `createClient` method that returns an initialized instance of an Anthropic client. Here's an example:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "00ec6d41",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { AnthropicVertex } from \"@anthropic-ai/vertex-sdk\";\n",
        "\n",
        "const customClient = new AnthropicVertex();\n",
        "\n",
        "const modelWithCustomClient = new ChatAnthropic({\n",
        "  modelName: \"claude-3-sonnet@20240229\",\n",
        "  maxRetries: 0,\n",
        "  createClient: () => customClient,\n",
        "});\n",
        "\n",
        "await modelWithCustomClient.invoke([{ role: \"user\", content: \"Hello!\" }]);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "68a85a61",
      "metadata": {},
      "source": [
        "## Citations\n",
        "\n",
        "Anthropic supports a [citations](https://docs.anthropic.com/en/docs/build-with-claude/citations) feature that lets Claude attach context to its answers based on source material supplied by the user. This source material can be provided either as [document content blocks](https://docs.anthropic.com/en/docs/build-with-claude/citations#document-types), which describe full documents, or as [search results](https://docs.anthropic.com/en/docs/build-with-claude/search-results), which describe relevant passages or snippets returned from a retrieval system. When `\"citations\": { \"enabled\": true }` is included in a query, Claude may generate direct citations to the provided material in its response.\n",
        "\n",
        "### Document example\n",
        "\n",
        "In this example we pass a [plain text document](https://docs.anthropic.com/en/docs/build-with-claude/citations#plain-text-documents). In the background, Claude [automatically chunks](https://docs.anthropic.com/en/docs/build-with-claude/citations#plain-text-documents) the input text into sentences, which are used when generating citations."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "d3f1c754",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  {\n",
            "    \"type\": \"text\",\n",
            "    \"text\": \"Based on the document, I can tell you that:\\n\\n- \"\n",
            "  },\n",
            "  {\n",
            "    \"type\": \"text\",\n",
            "    \"text\": \"The grass is green\",\n",
            "    \"citations\": [\n",
            "      {\n",
            "        \"type\": \"char_location\",\n",
            "        \"cited_text\": \"The grass is green. \",\n",
            "        \"document_index\": 0,\n",
            "        \"document_title\": \"My Document\",\n",
            "        \"start_char_index\": 0,\n",
            "        \"end_char_index\": 20\n",
            "      }\n",
            "    ]\n",
            "  },\n",
            "  {\n",
            "    \"type\": \"text\",\n",
            "    \"text\": \"\\n- \"\n",
            "  },\n",
            "  {\n",
            "    \"type\": \"text\",\n",
            "    \"text\": \"The sky is blue\",\n",
            "    \"citations\": [\n",
            "      {\n",
            "        \"type\": \"char_location\",\n",
            "        \"cited_text\": \"The sky is blue.\",\n",
            "        \"document_index\": 0,\n",
            "        \"document_title\": \"My Document\",\n",
            "        \"start_char_index\": 20,\n",
            "        \"end_char_index\": 36\n",
            "      }\n",
            "    ]\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "\n",
        "const citationsModel = new ChatAnthropic({\n",
        "  model: \"claude-3-5-haiku-latest\",\n",
        "});\n",
        "\n",
        "const messagesWithCitations = [\n",
        "  {\n",
        "    role: \"user\",\n",
        "    content: [\n",
        "      {\n",
        "        type: \"document\",\n",
        "        source: {\n",
        "          type: \"text\",\n",
        "          media_type: \"text/plain\",\n",
        "          data: \"The grass is green. The sky is blue.\",\n",
        "        },\n",
        "        title: \"My Document\",\n",
        "        context: \"This is a trustworthy document.\",\n",
        "        citations: {\n",
        "          enabled: true,\n",
        "        },\n",
        "      },\n",
        "      {\n",
        "        type: \"text\",\n",
        "        text: \"What color is the grass and sky?\",\n",
        "      },\n",
        "    ],\n",
        "  }\n",
        "];\n",
        "\n",
        "const responseWithCitations = await citationsModel.invoke(messagesWithCitations);\n",
        "\n",
        "console.log(JSON.stringify(responseWithCitations.content, null, 2));"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f7d19d17",
      "metadata": {},
      "source": [
        "### Search results example\n",
        "\n",
        "In this example, we pass in [search results](https://docs.anthropic.com/en/docs/build-with-claude/search-results) as part of our message content. This allows Claude to cite specific passages or snippets from your own retrieval system in its response.\n",
        "\n",
        "This approach is helpful when you want Claude to cite information from a specific set of knowledge, but you want to bring your own pre-fetched/cached content directly rather than having the model search or retrieve them automatically."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0fd441c8",
      "metadata": {},
      "outputs": [],
      "source": [
        "\n",
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "\n",
        "const citationsModel = new ChatAnthropic({\n",
        "  model: \"claude-3-5-haiku-latest\",\n",
        "  clientOptions: {\n",
        "    defaultHeaders: {\n",
        "      \"anthropic-beta\": \"search-results-2025-06-09\",\n",
        "    },\n",
        "  },\n",
        "});\n",
        "\n",
        "const messagesWithCitations = [\n",
        "  {\n",
        "    type: \"user\",\n",
        "    content: [\n",
        "      {\n",
        "        type: \"search_result\",\n",
        "        title: \"History of France\",\n",
        "        source: \"https://some-uri.com\",\n",
        "        citations: { enabled: true },\n",
        "        content: [\n",
        "          {\n",
        "            type: \"text\",\n",
        "            text: \"The capital of France is Paris.\",\n",
        "          },\n",
        "          {\n",
        "            type: \"text\",\n",
        "            text: \"The old capital of France was Lyon.\",\n",
        "          },\n",
        "        ],\n",
        "      },\n",
        "      {\n",
        "        type: \"text\",\n",
        "        text: \"What is the capital of France?\",\n",
        "      },\n",
        "    ],\n",
        "  },\n",
        "];\n",
        "\n",
        "const responseWithCitations = await citationsModel.invoke(messagesWithCitations);\n",
        "\n",
        "console.log(JSON.stringify(responseWithCitations.content, null, 2));"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0ae00bcb",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "#### Search results from a tool\n",
        "\n",
        "You can also use a tool to provide search results that the model can cite in its responses. This is well suited for RAG (or [Retrieval-Augmented Generation](https://en.wikipedia.org/wiki/Retrieval-augmented_generation)) workflows where Claude can decide when and where to retrieve information from. When returning this information as [search results](https://docs.anthropic.com/en/docs/build-with-claude/search-results), it gives Claude the ability to create citations from the material returned from the tool.\n",
        "\n",
        "Here's how you can create a tool that returns search results in the format expected by Anthropic's citations API:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "e83f7598",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "import { tool } from \"@langchain/core/tools\";\n",
        "\n",
        "// Create a tool that returns search results\n",
        "const ragTool = tool(\n",
        "  () => [\n",
        "    {\n",
        "      type: \"search_result\",\n",
        "      title: \"History of France\",\n",
        "      source: \"https://some-uri.com\",\n",
        "      citations: { enabled: true },\n",
        "      content: [\n",
        "        {\n",
        "          type: \"text\",\n",
        "          text: \"The capital of France is Paris.\",\n",
        "        },\n",
        "        {\n",
        "          type: \"text\",\n",
        "          text: \"The old capital of France was Lyon.\",\n",
        "        },\n",
        "      ],\n",
        "    },\n",
        "    {\n",
        "      type: \"search_result\", \n",
        "      title: \"Geography of France\",\n",
        "      source: \"https://some-uri.com\",\n",
        "      citations: { enabled: true },\n",
        "      content: [\n",
        "        {\n",
        "          type: \"text\",\n",
        "          text: \"France is a country in Europe.\",\n",
        "        },\n",
        "        {\n",
        "          type: \"text\",\n",
        "          text: \"The capital of France is Paris.\",\n",
        "        },\n",
        "      ],\n",
        "    },\n",
        "  ],\n",
        "  {\n",
        "    name: \"my_rag_tool\",\n",
        "    description: \"Retrieval system that accesses my knowledge base.\",\n",
        "    schema: z.object({\n",
        "      query: z.string().describe(\"query to search in the knowledge base\"),\n",
        "    }),\n",
        "  }\n",
        ");\n",
        "\n",
        "// Create model with search results beta header\n",
        "const model = new ChatAnthropic({\n",
        "  model: \"claude-3-5-haiku-latest\",\n",
        "  clientOptions: {\n",
        "    defaultHeaders: {\n",
        "      \"anthropic-beta\": \"search-results-2025-06-09\",\n",
        "    },\n",
        "  },\n",
        "}).bindTools([ragTool]);\n",
        "\n",
        "const result = await model.invoke([\n",
        "  {\n",
        "    role: \"user\",\n",
        "    content: \"What is the capital of France?\",\n",
        "  },\n",
        "]);\n",
        "\n",
        "console.log(JSON.stringify(result.content, null, 2));\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4d33db17",
      "metadata": {},
      "source": [
        "Learn more about how RAG works in LangChain [here](https://js.langchain.com/docs/concepts/rag/)\n",
        "\n",
        "Learn more about tool calling [here](https://js.langchain.com/docs/how_to/tool_calling/)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "14269f15",
      "metadata": {},
      "source": [
        "### Using with text splitters\n",
        "\n",
        "Anthropic also lets you specify your own splits using [custom document](https://docs.anthropic.com/en/docs/build-with-claude/citations#custom-content-documents) types. LangChain [text splitters](/docs/concepts/text_splitters/) can be used to generate meaningful splits for this purpose. See the below example, where we split the LangChain.js README (a markdown document) and pass it to Claude as context:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5e9f3213",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  {\n",
            "    \"type\": \"text\",\n",
            "    \"text\": \"Based on the documentation, I can provide you with a link to LangChain's tutorials:\\n\\n\"\n",
            "  },\n",
            "  {\n",
            "    \"type\": \"text\",\n",
            "    \"text\": \"The tutorials can be found at: https://js.langchain.com/docs/tutorials/\",\n",
            "    \"citations\": [\n",
            "      {\n",
            "        \"type\": \"content_block_location\",\n",
            "        \"cited_text\": \"[Tutorial](https://js.langchain.com/docs/tutorials/)walkthroughs\",\n",
            "        \"document_index\": 0,\n",
            "        \"document_title\": null,\n",
            "        \"start_block_index\": 191,\n",
            "        \"end_block_index\": 194\n",
            "      }\n",
            "    ]\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "import { MarkdownTextSplitter } from \"langchain/text_splitter\";\n",
        "\n",
        "function formatToAnthropicDocuments(documents: string[]) {\n",
        "  return {\n",
        "    type: \"document\",\n",
        "    source: {\n",
        "      type: \"content\",\n",
        "      content: documents.map((document) => ({ type: \"text\", text: document })),\n",
        "    },\n",
        "    citations: { enabled: true },\n",
        "  };\n",
        "}\n",
        "\n",
        "// Pull readme\n",
        "const readmeResponse = await fetch(\n",
        "  \"https://raw.githubusercontent.com/langchain-ai/langchainjs/master/README.md\"\n",
        ");\n",
        "\n",
        "const readme = await readmeResponse.text();\n",
        "\n",
        "// Split into chunks\n",
        "const splitter = new MarkdownTextSplitter({\n",
        "  chunkOverlap: 0,\n",
        "  chunkSize: 50,\n",
        "});\n",
        "const documents = await splitter.splitText(readme);\n",
        "\n",
        "// Construct message\n",
        "const messageWithSplitDocuments = {\n",
        "  role: \"user\",\n",
        "  content: [\n",
        "    formatToAnthropicDocuments(documents),\n",
        "    { type: \"text\", text: \"Give me a link to LangChain's tutorials. Cite your sources\" },\n",
        "  ],\n",
        "};\n",
        "\n",
        "// Query LLM\n",
        "const citationsModelWithSplits = new ChatAnthropic({\n",
        "  model: \"claude-3-5-sonnet-latest\",\n",
        "});\n",
        "const resWithSplits = await citationsModelWithSplits.invoke([messageWithSplitDocuments]);\n",
        "\n",
        "console.log(JSON.stringify(resWithSplits.content, null, 2));"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a5bb5ca-c3ae-4a58-be67-2cd18574b9a3",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all ChatAnthropic features and configurations head to the API reference: https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
